﻿using jvm.instructions.common;
using jvm.rtda;
using jvm.rtda.frame;
using jvm.rtda.heap;
using jvm.rtda.heap.clazz;
using jvm.rtda.heap.clazz.cp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.instructions.references
{
    class GET_STATIC : Index16Instruction
    {
        public override void Execute(JFrame frame)
        {
            JConstantPool pool = frame.method.jClass.constantPool;
            FieldRef fieldRef = pool.GetConstant<FieldRef>(index);
            JField field = fieldRef.ResolvedField();
            JClass jClass = field.jClass;
            if (!jClass.inited)
            {
                frame.RevertPc();
                jClass.Init(frame.thread);
                return;
            }
            // todo init class
            if (!field.Is(AccessFlags.ACC_STATIC))
            {
                Console.WriteLine("java.lang.IncompatibleClassChangeError");
                Environment.Exit(0);
            }

            char descriptor = field.descriptor[0];
            uint slotId = field.slotId;
            Slots slots = jClass.staticVars;
            JOperandStack stack = frame.operandStack;
            switch (descriptor)
            {
                case 'Z':
                case 'B':
                case 'C':
                case 'S':
                case 'I':
                    stack.PushInt(slots.GetInt(slotId));
                    break;
                case 'F':
                    stack.PushFloat(slots.GetFloat(slotId));
                    break;
                case 'J':
                    stack.PushLong(slots.GetLong(slotId));
                    break;
                case 'D':
                    stack.PushDouble(slots.GetDouble(slotId));
                    break;
                case 'L':
                case '[':
                    //if (jClass.name.Equals("java/lang/System"))
                    //{
                    //    stack.PushRef(null);
                    //}
                    //else
                    //{
                        stack.PushRef(slots.GetRef(slotId));
                    //}

                    break;
            }
        }
    }
}
